﻿using System;
using System.Linq;
using System.Text;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;
using System.Threading;
using System.IO;
using System.Reflection;
using System.Collections.Generic;
using System.Xml.Linq;

namespace DuplexDeviceEvent
{
    public class DeviceEventService : IDeviceEventService, IPolicyRetriever
    {
        public void Connect(string id)
        {
            IDeviceEventServiceClient client = OperationContext.Current.GetCallbackChannel<IDeviceEventServiceClient>();
            DeviceEventRunner.Register(client, id);
        }

        #region Cross Domain Policy Implementation

        private Stream StringToStream(string result)
        {
            WebOperationContext.Current.OutgoingResponse.ContentType = "application/xml";
            return new MemoryStream(Encoding.UTF8.GetBytes(result));
        }

        public Stream GetSilverlightPolicy()
        {
            string result = @"<?xml version=""1.0"" encoding=""utf-8""?><access-policy><cross-domain-access><policy><allow-from http-request-headers=""*""><domain uri=""*""/></allow-from><grant-to><resource path=""/"" include-subpaths=""true""/></grant-to></policy></cross-domain-access></access-policy>";
            return StringToStream(result);
        }

        public Stream GetFlashPolicy()
        {
            string result = @"<?xml version=""1.0""?><!DOCTYPE cross-domain-policy SYSTEM ""http://www.macromedia.com/xml/dtds/cross-domain-policy.dtd""><cross-domain-policy><allow-access-from domain=""*"" /></cross-domain-policy>";
            return StringToStream(result);
        }
        #endregion
    }
}
